package com.jingxuan.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.jingxuan.common.result.Result;
import com.jingxuan.dto.request.RecordVisitRequest;
import com.jingxuan.dto.request.RecordLinkClickRequest;
import com.jingxuan.dto.response.VisitStatsResponse;
import com.jingxuan.interceptor.AuthInterceptor;
import com.jingxuan.service.VisitStatsService;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;

/**
 * 访问统计控制器
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/stats")
public class VisitStatsController {

    @Autowired
    private VisitStatsService visitStatsService;

    /**
     * 记录页面访问（用于前端调用）
     */
    @PostMapping("/visit")
    public Result<Void> recordVisit(@Valid @RequestBody RecordVisitRequest request, HttpServletRequest httpRequest) {
        String ipAddress = getClientIpAddress(httpRequest);
        String userAgent = httpRequest.getHeader("User-Agent");
        Long userId = AuthInterceptor.getCurrentUserId();
        
        visitStatsService.recordPageVisit(request, ipAddress, userAgent, userId);
        log.debug("记录页面访问: visitorId={}", request.getVisitorId());
        return Result.success();
    }

    /**
     * 记录链接跳转（用于前端调用）
     */
    @PostMapping("/link-click")
    public Result<Void> recordLinkClick(@Valid @RequestBody RecordLinkClickRequest request) {
        Long userId = AuthInterceptor.getCurrentUserId();
        visitStatsService.recordLinkClick(request, userId);
        log.debug("记录链接跳转: visitorId={}, productId={}", request.getVisitorId(), request.getProductId());
        return Result.success();
    }

    /**
     * 获取访问统计数据（管理员接口）
     * @param period 时间周期：6d（近6天）、30d（近30天）、quarter（近一季度）、year（近一年）
     */
    @GetMapping("/overview")
    public Result<VisitStatsResponse> getVisitStats(
            @RequestParam(value = "period", defaultValue = "6d") String period) {
        VisitStatsResponse response = visitStatsService.getVisitStats(period);
        log.info("获取访问统计: period={}, todayUv={}, todayClicks={}", 
            period, response.getTodayUv(), response.getTodayLinkClicks());
        return Result.success(response);
    }

    /**
     * 刷新统计数据（管理员接口）
     */
    @PostMapping("/refresh")
    public Result<Void> refreshStats() {
        visitStatsService.refreshDailyStats();
        log.info("刷新统计数据成功");
        return Result.success();
    }

    /**
     * 获取客户端真实IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 多个代理时，第一个IP为客户端真实IP
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }
}

